import React from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale';
import { message, Modal, Select } from 'antd';
import { reqeustRemoteValidate } from './request';

const Option = Select.Option;
const OptGroup = Select.OptGroup;

export default {
  /**
   * 官网见：https://ant.design/components/pagination-cn/
   * antd Table 分页处理.简单封装
   * @param data
   * @param callback
   */
  pagination(data, callback) {
    const total = formatMessage({ id: 'ours.curd.list.page.total' }); //共
    const item = formatMessage({ id: 'ours.curd.list.page.item' }); //条
    return {
      //页码改变的回调，参数是改变后的页码及每页条数
      onChange: current => {
        //不是一页这里就回调
        if (data.page.currPage !== current) {
          callback(current);
        }
      },
      //pageSize 变化的回调
      onShowSizeChange: (current, size) => {
        callback(current, size);
      },
      current: data.page.currPage,
      pageSize: data.page.pageSize,
      total: data.page.totalCount,
      showTotal: () => `${total}${data.page.totalCount}${item}`,
      showQuickJumper: true,
      pageSizeOptions: ['10', '30', '50', '100'],
      showSizeChanger: true,
    };
  },
  /**
   * 生成select options
   * @param data eg: [{id: '0', name: '全部'}, {id: '1', name: '北京'}, {id: '2', name: '上海'}, {id: '3', name: '天津'}, {id: '4', name: '杭州'}]
   * @returns {Array}
   *
   * 第二种情况，支持 optGroup
   */
  getOptionList(data) {
    if (!data) {
      return [];
    }
    const options = [];
    data.forEach(item => {
      //第一种情况
      if (item.id || item.name) {
        const { id, name, ...other } = item;
        options.push(
          <Option value={id} key={id} {...other}>
            {name}
          </Option>
        );
      } else {
        //第二种情况，支持 optGroup
        /* eslint-disable no-restricted-syntax */
        for (const [key, value] of Object.entries(item)) {
          const optionSubs = [];
          //add sub Options
          if (value !== null && value !== undefined) {
            value.forEach(itemSub => {
              optionSubs.push(
                <Option value={itemSub.id} key={itemSub.id}>
                  {itemSub.name}
                </Option>
              );
            });
            //add OptGroup
            options.push(<OptGroup label={key}>{optionSubs}</OptGroup>);
          }
        }
      }
    });
    return options;
  },
  /**
   * @param jsonObj eg: {'1': '字符型','2': '数字型','3': '时间型','4': 'Boolean型', '5': '数组型','6': '文件型'  '7': '图片型'}
   * @returns {Array}
   * [{id: '0', name: '全部'}, {id: '1', name: '北京'}, {id: '2', name: '上海'}, {id: '3', name: '天津'}, {id: '4', name: '杭州'}]
   *
   *
   * 第二种情况，支持 optGroup
   * eg:  {'android': {},'ios': { 'ios_all': 'IOS全部', 'ios_apns_production_true': 'IOS生产'}};
   * @returns {Array}
   * [{android: []}, {ios: [{id: 'ios_all', name: 'IOS全部'},{id: 'ios_apns_production_true', name: 'IOS生产'}]}];
   */
  /* eslint-disable no-restricted-syntax */
  getOptionJsonObjToArr(jsonObj) {
    let json = jsonObj;
    if (typeof jsonObj === 'string') {
      json = JSON.parse(jsonObj);
    }
    const data = [];
    if (Object.entries(json).length <= 0) {
      return data;
    }
    for (const [key, value] of Object.entries(json)) {
      if (typeof value === 'object') {
        //第二种情况，支持 optGroup
        const options = [];
        for (const [keySub, valueSub] of Object.entries(value)) {
          options.push({ id: keySub, name: valueSub });
        }
        const group = {};
        group[key] = options;
        data.push(group);
      } else {
        //第一种情况
        data.push({ id: key, name: value });
      }
    }
    return data;
  },
  /**
   * antd Table 选择事件回调.简单封装； 包含：单选、全选、全不选
   * @param selectedIndexs 官方名称：selectedRowKeys; row.index 行的下标集合；
   * @param selectedRows 所有行数据的集合
   * @param selectedIds 所有行主键的集合
   */
  onSelectRow(selectedIndexs, selectedRows, selectedIds) {
    if (selectedIds) {
      this.setState({
        ...selectedIndexs,
        ...selectedRows,
        ...selectedIds,
      });
    } else {
      this.setState({
        ...selectedIndexs,
        ...selectedRows,
      });
    }
  },
  showAlert(info, type = 'warning') {
    Modal[type]({
      title: null,
      content: info,
    });
  },
  showMessage(msg, type = 'info') {
    message[type](msg);
  },
  showConfirm(msg, callback) {
    Modal.confirm({
      content: msg,
      onOk() {
        callback();
      },
    });
  },
  getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  },
};

/**
 * 判断是否有对应的按钮权限
 * @param permission
 * @returns {boolean}
 *
 * @see menu/getMenuData
 * @see window.permissions
 */
export function hasPermission(permission) {
  window.permissions = window.permissions || [];
  return window.permissions.indexOf(permission) > -1;
}

/**
 * https://ant-design.gitee.io/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
 * 远程校验实例
 * @param method 请求方式POST、GET、PUT；必填
 * @param url；必填
 * @param otherField 可选参数，如果不止一个参数，这写上其他参数：eg: {username:'zhangsan', age: 15}
 */
export function rulesRemote(method, url, otherField = {}) {
  return {
    validator: (rule, value, callback) => {
      let body = {};
      body[rule.field] = value;
      if (otherField) {
        body = { ...body, ...otherField };
      }

      reqeustRemoteValidate(url, {
        method,
        body,
      })
        .then(msg => {
          callback(); // 校验通过
        })
        .catch(error => {
          callback(error); // 校验未通过
        });
    },
  };
}

/**
 * 正则：pattern、REGEXP
 */
export function rulesReg(rule) {
  /* eslint-no-useless-escape*/ //压制无效的转义字符
  const validatorRules = {
    digits: [/^\d+$/, '请填写数字'],
    letters: [/^[a-z]+$/i, '请填写字母'],
    date: [/^\d{4}-\d{2}-\d{2}$/, '请填写有效的日期，格式:yyyy-mm-dd'],
    time: [/^([01]\d|2[0-3])(:[0-5]\d){1,2}$/, '请填写有效的时间，00:00到23:59之间'],
    email: [
      /^[\w\+\-]+(\.[\w\+\-]+)*@[a-z\d\-]+(\.[a-z\d\-]+)*\.([a-z]{2,4})$/i,
      '请填写有效的邮箱',
    ],
    url: [/^(https?|s?ftp):\/\/\S+$/i, '请填写有效的网址'],
    qq: [/^[1-9]\d{4,}$/, '请填写有效的QQ号'],
    IDcard: [
      /^\d{6}(19|2\d)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)?$/,
      '请填写正确的身份证号码',
    ],
    tel: [
      /^(?:(?:0\d{2,3}[\- ]?[1-9]\d{6,7})|(?:[48]00[\- ]?[1-9]\d{6}))$/,
      '请填写有效的电话号码',
    ],
    mobile: [/^1[3-9]\d{9}$/, '请填写有效的手机号'],
    mobile_tel: [
      /^(?:(?:0\d{2,3}[\- ]?[1-9]\d{6,7})|(?:[48]00[\- ]?[1-9]\d{6}))$|^(1[3-9]\d{9})$/,
      '请输入正确的手机号码或者电话号码',
    ],
    zipcode: [/^\d{6}$/, '请检查邮政编码格式'],
    chinese: [/^[\u0391-\uFFE5]+$/, '请填写中文字符'],
    username: [/^\w{3,50}$/, '请填写3-50位数字、字母、下划线'],
    password: [/^[\S]{6,16}$/, '请填写6-16位字符，不能包含空格'],
    number: [/^(-?\d+)(\.\d+)?$/, '请输入有效数字'],
    D_card: [
      /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[A-Z])$/,
      '请输入正确的身份证号码',
    ],
    postcode: [/^[1-9]\d{5}$/, '邮政编码格式不正确'],
    plus: [/^[0-9]*[0-9][0-9]*$/, '请输入一个正整数'],
    money: [/^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/, '请输入正确的数字'],
    sort: [/^([1-6])?$/, '请输入1-6的数字'],
    exchangeCode: [/^\s*\d{16}\s*$/, '请输入16位数字的兑换码'],
    propotion: [/^(0|1|1\.[0]*|0?\.[\d]+)$/, '请输入0到1之间的数字'],
    format: [/^(\d*,*)*$/, '请输入格式 数字,数字'],
    startWeigt: [/^\d+(\.\d{1})?$/, '只能输入正一位小数、整数'],
    starWeigt: [/^\d+(\.\d{1,2})?$/, '只能输入正两位小数、整数'],
    standardwight: [/^([1-9][\d]{0,3}|0)(\.[\d]{1,2})?$/, '最大9999.99'],
    plusNum: [/^[0-9]\d*(\.\d+)?$/, '必须大于0'],
    plusNums: [/^[1-9]\d*(\.\d+)?$/, '必须大于0'],
    plusnums: [/^([1-9][\d]{0,1}|0)(\.[\d]{1,4})?$/, '1到100之间，小数点后最多4位'],
    plusnums1: [/^1$|^0(\.\d{1,3})?$/, '0.001-1范围内的数字，小数位最多3位'],
    plusnums2: [/^1.00$|^0(\.\d{1,2})?$/, '0到1之间，保留两位小数'],
    plusnums3: [/^([1-9][\d]{0,1}|0)(\.[\d]{1,5})?$/, '1到100之间，小数点后最多5位'],
    plusnums4: [/^(0(\.\d{1,2})?|1(\.0{1,2})?)$/, '0到1之间，保留两位小数'],
    plusnums5: [
      /((?<![\.\d])[1-9](?![\.\d]))|([0-9]\.[0-9](?![\d\.]))/,
      '0到10之间，不包括0与10，小数点后最多1位',
    ],
    shopno: [/^\w{1,12}$/, '格式不正确'],
    nozero: [/^(\+|-)?([1-9][0-9]*(\.\d+)?|(0\.(?!0+$)\d+))$/, '必须大于0'],
    chineseletternum: [/^[\u4E00-\u9FA5A-Za-z0-9]{4,20}$/, '请输入4到20位中英文、数字'],
    roleName: [/^[\u4E00-\u9FA5A-Za-z0-9]{2,30}$/, '请输入2到30位中英文、数字'],
    menuName: [
      /^[\u4E00-\u9FA5A-Za-z0-9_【】]{2,30}$/,
      '菜单名称必须是2到30位中英文、数字、下划线、中文中括号',
    ], //不能输入其他英文或者中文的标点符号否则会出问题
    creditcard: [/^\d+$/, '请输入合法的信用卡号'],
    busIntDeadline: [/^([12][0-9]|[3][0-5]|36|[1-9])$/, '整数1~36'],
    busIntSum: [/^([3-9]\d|[1-9]\d{2}|[1-4]\d{3}|5000)$/, '整数30~5000'],
    busIntMonthlyrate: [
      /^(([0-2]\.[0])|([0-2]\.[0][0])|([0-2]\.[0][0][0])|(([0]\.\d{1,3}|[0-1]\.\d{1,3})))$/,
      '小数（可精确到3位）0~2,单位%',
    ],
    busIntServicesfee: [
      /^(([0-1][0]\.[0])|([0-1][0]\.[0][0])|([0-1][0]\.[0][0][0])|(([0]\.\d{1,3}|[0-9]\.\d{1,3})))$/,
      '小数（可精确到3位）0~10,单位%',
    ],
    int_0_10000: [/^([1-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|10000)$/, '整数（1~10000）'],
    busInt: [/^(([0-9]\d{0,5})|999999)$/, '整数（1~999999)'],
    atext: [
      /(^[1-9]\d{0,7}$|^100000000$|^100000000(\.[\d]{1,2})\d+?|^0$)|(^[1-9]\d{0,7}\.{1}\d+)|(^0\.{1}\d+)/,
      '小数（0~100000000），以文本形式存储（即保留小数点后输入的任何内容）',
    ],
    busChdArea: [
      /(^[1-9]\d{0,3}$|^2000$|^2000(\.[\d]{1,2})\d+?|^0$)|(^[1-9]\d{0,3}\.{1}\d+)|(^0\.{1}\d+)/,
      '小数（0~2000），以文本形式存储（即保留小数点后输入的任何内容）',
    ],
    money_0_200000: [
      /^(([0-9]\d{0,4})(\.[\d]{1,2})?|([1]\d{0,5})(\.[\d]{1,2})?|200000|200000\.[0]|200000\.[0][0])$/,
      '实数0~200000，保留两位小数,单位万',
    ],
    money_0_999999: [
      /^(([0-9]\d{0,5})(\.[\d]{1,2})?|999999|999999\.[0]|999999\.[0][0])$/,
      '实数0~999999，保留两位小数,单位元',
    ],
    money_0_100: [
      /^(([0-9]\d{0,1})(\.[\d]{1,2})?|100|100\.[0]|100\.[0][0])$/,
      '实数0~100，保留两位小数,单位%',
    ],
    double_0_100: [
      /^(([0-9]\d{0,1})(\.[\d]{1,2})?|100|100\.[0]|100\.[0][0])$/,
      '实数0~100，保留两位小数',
    ],
    number_0_999: [/^([0-9]\d{0,3})?$/, '请输入0-999的数字'],
    money1_0_9999999999999999: [
      /^(([0-9]\d{0,15})(\.[\d]{1,4})?|9999999999999999|9999999999999999\.[0]|9999999999999999\.[0][0])$/,
      '正数0~9999999999999999，保留四位小数,单位元',
    ],
    money_0_9999999999999999: [
      /^(([0-9]\d{0,15})(\.[\d]{1,4})?|9999999999999999|9999999999999999\.[0]|9999999999999999\.[0][0])$/,
      '正数0~9999999999999999，保留四位小数,单位万元',
    ],
    map: [/^([0-9]+\.{0,1}[0-9]{0,})+\,+([0-9]+\.{0,1}[0-9]{0,})$/, '请填写正确的坐标'],
    regex_BizLience: [/^([0-9a-zA-Z]{18}$|\d{15}$)/, '请填写正确的营业执照'],
    car_vin: [/^([A-Za-z0-9]{17})$/, 'VIN车架号17位'],
    car_sn: [/^([\u4e00-\u9fa5]{1}[A-Za-z]{1}[A-Za-z0-9]{5,6})$/, '请输入7位的车牌号'],
    car_driving_licence: [
      /^([\u4e00-\u9fa5]{1}[A-Za-z]{1}[A-Za-z0-9]{5})$/,
      '请输入12位的驾驶证档案编号',
    ],
    letter_num__: [/^\w+$/, '请输入字母或者数字或者英文的符号'],
  };
  const ruleObj = validatorRules[rule];
  return {
    pattern: ruleObj[0],
    message: ruleObj[1],
  };
}
